<template>
  <div class="component add-project-component">
    <Form ref="projectForm" :model="projectModel" :rules="projectRule" :label-width="80">
      <Form-item label="项目名称" prop="name">
        <Input v-model="projectModel.name" placeholder="请输入"></Input>
      </Form-item>
      <Form-item label="项目描述" prop="describe">
        <Input type="textarea" v-model="projectModel.describe" placeholder="请输入"></Input>
      </Form-item>
    </Form>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import { Projects } from '/imports/collections'

  export default {
    name: 'add-project',
    meteor: {
      $subscribe: {
        projects: []
      }
    },
    data () {
      return {
        projectModel: {
          name: '', // 项目名称
          describe: '' // 项目描述
        },
        projectRule: {
          name: [
            { required: true, message: '请填写项目名称', trigger: 'blur' },
            { validator: this.validateProjectName, trigger: 'blur' }
          ],
          describe: [
            { type: 'string', max: 100, message: '不能超过100个字', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      ...mapState({
        user: state => state.user
      })
    },
    methods: {
      validateProjectName (rule, value, callback) {
        if (Projects.findOne({ name: this.projectModel.name })) {
          callback.call(this, '该项目名称已存在')
        } else {
          callback()
        }
      },
      /**
       * 添加项目
       */
      submit (dialog) {
        dialog.loading = false
        this.$refs.projectForm.validate((valid) => {
          // 验证失败
          if (!valid) {
            this.$nextTick(() => {
              dialog.loading = true
            })
            return
          }

          Projects.insert(Object.assign(this.projectModel, {
            creator: this.user.id,
            createDate: new Date()
          }), (error, result) => {
            if (error) {
              dialog.loading = true
            } else {
              this.$Message.success('添加成功')
              this.$nextTick(() => {
                this.reset()
                dialog.loading = true
                dialog.visible = false
              })
            }
          })
        })
      },
      /**
       * 重置表单
       */
      reset () {
        this.$nextTick(() => {
          this.$refs.projectForm.resetFields()
        })
      }
    },
    mounted () {}
  }
</script>
<style scoped>


</style>
